package com.sptus.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.sptus.framework.config.MyBatisConfig;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.sptus.**.mapper.master,com.sptus.mapper.master", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterMybatisConfig {
 
    @Autowired
    @Qualifier("masterDataSource")
    private DataSource masterDataSource;
 
 
    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();//mybatis-plus
//        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();//mybatis
        sessionFactory.setDataSource(masterDataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        // ... 其他配置，比如MapperLocations等
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setDefaultFetchSize(100);
        Interceptor[] plugins = {new MyBatisConfig().mybatisPlusInterceptor()};
        sessionFactory.setPlugins(plugins);
        configuration.setDefaultStatementTimeout(30);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/**.xml"));
        sessionFactory.setTypeAliasesPackage("com.sptus.**.domain");
        sessionFactory.setConfiguration(configuration);
        return sessionFactory.getObject();
    }
 
     /**
     * 创建事务管理器
     * 事务参考https://www.jianshu.com/p/2014d9a7b41d
     * @return
     */
    @Bean(name = "mastTransactionManager")
    @Primary
    public DataSourceTransactionManager erpTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource);
    }
 
    /**
     * 创建sqlSession模板
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "masterSqlSessionTemplate")
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}